
from app01 import models
from app01.utils.bootstrape import BootStrapModelForm

from django.core.validators import ValidationError



class PrettyModelFrom(BootStrapModelForm):
    #校验方法一：
    # mobile=forms.CharField(
    #     label='手机号',
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式错误')]
    # )
    class Meta:
        model=models.PrettyNum
        fields=['mobile','price','level','status']
        # fields="__all__"
        # exclude=['level']

    def clean_mobile(self):
        txt_mobile=self.cleaned_data['mobile']
        exists=models.PrettyNum.objects.filter(mobile=txt_mobile)
        if len(txt_mobile) != 11:
            raise ValidationError('格式错误')
        if exists:
            raise ValidationError('手机号已存在')
        return txt_mobile

class PrettyEditModelFrom(BootStrapModelForm):
    # mobile=forms.CharField(label='手机号')
    class Meta:
        model=models.PrettyNum
        fields=['mobile','price','level','status']
        # fields="__all__"
        # exclude=['level']
   
    def clean_mobile(self):
        txt_mobile=self.cleaned_data['mobile']
        exists=models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile)
        if len(txt_mobile) != 11:
            raise ValidationError('格式错误')
        if exists:
            raise ValidationError('手机号已存在')
        return txt_mobile